package web.security;

import framework.security.FunctionPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import security.filters.AuthenticationServletFilter;
import security.service.SecurityContext;

import javax.servlet.annotation.WebFilter;
import java.util.List;

/**
 * 授权过滤器
 */
@Slf4j
@Order(1)
@WebFilter
@Component
@ConditionalOnProperty(name = "sys.security.enabled", havingValue = "true", matchIfMissing = true)
public class AuthenticationFilter extends AuthenticationServletFilter {

    public AuthenticationFilter(SecurityContext securityContext) {
        super(securityContext);
    }

    @Override
    protected List<FunctionPermission> loadFunctionPermissionList() {
        List<FunctionPermission> fpl = super.loadFunctionPermissionList();

        // 重载： 添加系统必要的需要授权访问的路径配置, 以下配置也可以通过菜单配置
        // 通常为系统支持性非业务性的接口或地址在此配置，业务地址通过菜单配置

        // --------------------
        // 允许匿名访问的的系统路径
        fpl.add(new FunctionPermission("/", "ANON", null));
        fpl.add(new FunctionPermission("/favicon.ico", "ANON", null));
        fpl.add(new FunctionPermission("/robots.txt", "ANON", null));
        // 开放资源
        fpl.add(new FunctionPermission("/file/g/**", "ANON", null));
        fpl.add(new FunctionPermission("/pub/**", "ANON", null));
        // 开放静态资源
        fpl.add(new FunctionPermission("/js/**", "ANON", null));
        fpl.add(new FunctionPermission("/css/**", "ANON", null));
        fpl.add(new FunctionPermission("/img/**", "ANON", null));
        // 开放swagger
        fpl.add(new FunctionPermission("/swagger-ui/**", "ANON", null));
        fpl.add(new FunctionPermission("/swagger-resources/**", "ANON", null));
        fpl.add(new FunctionPermission("/v3/api-docs", "ANON", null));
        fpl.add(new FunctionPermission("/v2/api-docs", "ANON", null));

        // --------------------
        // 需要授权才能访问的系统路径
        fpl.add(new FunctionPermission("/pub/status", "AUTH", null));
        fpl.add(new FunctionPermission("/file/s/**", "AUTH", null));
        //我的账号信息
        fpl.add(new FunctionPermission("/my/**", "AUTH", null));

        // 将登入/登出路径设置为匿名访问
        if (StringUtils.hasText(getSecurityConfig().getLoginPath()))
            fpl.add(new FunctionPermission(getSecurityConfig().getLoginPath(), "ANON", null));
        if (StringUtils.hasText(getSecurityConfig().getLogoutPath()))
            fpl.add(new FunctionPermission(getSecurityConfig().getLogoutPath(), "ANON", null));

        //
        return fpl;
    }
}
